<template>
  <Layout>
      <div v-if="!answerShow" v-show="!answerShow">
          <Form :label-width="120" ref="formInline" :model="formInline">
              <Row class="query-form">
                  <Col span="8">
                      <FormItem label="试卷名称：" prop="paperInfo">
                          <Input v-model="formInline.paperInfo" />
                      </FormItem>
                  </Col>
                  <Col span="8" offset="8">
                      <Button @click="cancel" class="ivu-btn-reset">重置</Button>
                      <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                  </Col>
              </Row>
          </Form>
          <Alert type="warning" v-if="answerNum>0">{{this.answerNumTitle}}</Alert>
          <Table ref='table'  :loading="loading" border :columns="paperColumns"
                 :data="paperData" no-data-text="没有查询到相关数据!" :height="tableHeight" highlight-row stripe size="small"></Table>
          <Row style="margin-right:10px;">
              <Col span="24">
                  <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                        @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
              </Col>
          </Row>
      </div>

      <answer
              v-if="answerShow"
              ref="childAnswer"
              :show="answerShow"
              :paper="paper"
              :is-operation="isOperation"
              @closeAnswer="close"
      />
    </Layout>
</template>

<script>

    import {Api} from '@/api'
    import qs from "qs";
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import {formatDate} from '@/tools/index'
    import answer from '../answer/answer'

    export default {
        name: "testList",
        components: {answer},
        data(){
            return{
                loading: true,
                tableHeight: '',
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                formInline:{
                    paperInfo: '',
                },
                paperColumns: [
                    {type: 'index', title: '编号', width: 80, align: 'center', fixed: 'left'},
                    {title: '所属公司', align: 'center', minWidth:200, key: 'companyName'},
                    {title: '试卷名称', minWidth:180, align: 'center', key: 'paperInfo',tooltip:true},
                    {title: '开始日期', align: 'center', minWidth:100, key: 'examDateStart',render:(h, params)=> {
                            if (!params.row['examDateStart']) return "";
                            return h('span', formatDate(new Date(params.row['examDateStart']), "yyyy-MM-dd"))}},
                    {title: '结束日期', align: 'center', minWidth:100, key: 'examDateEnd',render:(h, params)=> {
                            if (!params.row['examDateEnd']) return "";
                            return h('span', formatDate(new Date(params.row['examDateEnd']), "yyyy-MM-dd"))}},

                    {title: '试卷状态', align: 'center', minWidth:80, key: 'paperState', render:(h,params)=>{
                            return h('div',[h('span',params.row.paperState === '0'?'关闭':params.row.paperState === '1'?'开启':'--')]);
                        }
                    },
                    {title: '允许答题次数', minWidth:100, align: 'center', key: 'examFrequency'},
                    {title: '已答题次数', minWidth:100, align: 'center', key: 'answeredNum'},
                    {title: '考试成绩', minWidth:90, align: 'center', key: 'paperResult'},
                    {title: '考试结果', minWidth:120, align: 'center', key: 'paperResultName'},
                    {title: '考试开始时间', minWidth:160, align: 'center', key: 'examStartTime',render:(h, params)=> {
                            if (!params.row['examStartTime']) return "";
                            return h('span', formatDate(new Date(params.row['examStartTime']), "yyyy-MM-dd hh:mm:ss"))}},
                    {title: '考试结束时间', minWidth:160, align: 'center', key: 'examEndTime',render:(h, params)=> {
                            if (!params.row['examEndTime']) return "";
                            return h('span', formatDate(new Date(params.row['examEndTime']), "yyyy-MM-dd hh:mm:ss"))}},
                    {title: '考试时长', minWidth:90, align: 'center', key: 'examTime',render:(h,params)=>{
                            return h('div',[ h('span',!params.row.paperResultName?'':params.row.examTime+'(分钟)')]);}},
                            {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 160,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.answerOpen(params.row,1)
                                        }
                                    }
                                }, '答题'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.answerOpen(params.row,2)
                                        }
                                    }
                                }, '查看试卷')
                            ]);
                        }
                    }
                ],
                paperData: [],

                answerNum:0,
                answerNumTitle:'',
                isOperation:false,
                paper:{},
                answerShow:false

            }
        },
        beforeRouteLeave(to, from, next) {
            if (this.answerShow && this.isOperation) {
                setTimeout(() => {
                    this.$Modal.confirm({
                        title: '提示',
                        content: '<p>未交卷,是否放弃此次考试答题？？</p>',
                        onOk: () => {
                            // 调用子组件答题
                            this.$refs.childAnswer.giveAnswer()
                            next(false)
                        },
                        onCancel: () => {
                        }
                    });
                }, 200)
            } else {
                next()
            }
        },
        mounted(){
            this.tableHeight = window.innerHeight*0.85 - this.$refs.table.$el.offsetTop-40;
            this.query();
        },
        methods: {
            close() {
                this.paper = {}
                this.answerShow = false
                this.query()
            },
            betweenTime(starTime, endTime) {
                var curTime = formatDate(new Date(), "yyyy-MM-dd")
                starTime = formatDate(new Date(starTime), "yyyy-MM-dd")
                endTime = formatDate(new Date(endTime), "yyyy-MM-dd")
                if (curTime >= starTime && curTime <= endTime) {
                    return true
                }
                return false
            },
            answerOpen(row, type) {
                if (type === 1) {
                    if (row.paperState === '0') {
                        this.$Message.warning('试卷已关闭不可答题！')
                        return
                    }
                    // 不在答题时间范围 不能答题
                    const flag = this.betweenTime(row.examDateStart, row.examDateEnd)
                    if (!flag) {
                        this.$Message.warning('当前时间不再考试答题时间范围,无法答题！')
                        return
                    }
                    if (row.examFrequency > row.answeredNum) {
                        // 重新答题 加提示语
                        if (row.answeredNum > 0) {
                            this.$Modal.confirm({
                                title: '提示',
                                content: '<p>是否重新答题？</p>',
                                onOk: () => {
                                    this.isOperation = true
                                    this.paper = row
                                    this.answerShow = true
                                },
                                onCancel: () => {
                                }
                            });
                        } else {
                            this.isOperation = true
                            this.paper = row
                            this.answerShow = true
                        }
                    } else {
                        this.$Message.warning('您已经达到最大答题次数,无法进行答题！')
                        return
                    }
                } else {
                    if (row.paperResultName === '' || row.paperResultName == null) {
                        this.$Message.warning('请先进行答题！')
                        return
                    } else {
                        this.isOperation = false
                        this.paper = row
                        this.answerShow = true
                    }
                }
            },
            query(){
                this.loading = true;
                this.getNeedAnswerNum()
                let data = {
                    page: this.pagedata.currentPage,
                    rows: this.pagedata.pageSize,
                    createUserId: sessionStorage('userId').getObject('userId').userId,
                };
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.paper+'/getPaperResultPageList',{
                    params:data,
                    paramsSerializer: params => {
                        return qs.stringify(params, { indices: false })
                    }
                }).then((res) => {
                    this.paperData = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch( e => {
                    this.$Message.error('请求失败');
                });
            },
            // 获取答题数
            getNeedAnswerNum() {
                this.$http.get(Api.paper+'/getNeedAnswerNum').then(res => {
                    if (res.data.status === 200) {
                        this.answerNum = res.data.data
                        if (this.answerNum > 0) {
                            this.answerNumTitle = '您当前有' + this.answerNum + '个答题任务未完成，请尽快执行 ！！！'
                        }
                    } else {
                        this.$Message.error(res.data.msg)
                    }
                })
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            cancel(){
                this.formInline = {};
                this.query();
            },
        }
    }
</script>

<style lang='css' scoped>
@import '../../../../index.css';
</style>
